package com.oue.iot.device;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jrain.fw.business.utils.BusinessUtils;
import jrain.fw.core.business.Business;
import jrain.fw.core.business.BusinessConst;
import jrain.fw.core.business.BusinessMethod;
import jrain.fw.core.business.BusinessRequest;
import jrain.fw.core.business.BusinessResponse;
import jrain.fw.core.dao.SqlRunner;
import jrain.fw.core.dao.bean.PageObj;
import jrain.fw.core.utils.FwUtils;
import jrain.fw.dao.common.utils.SqlUtils;
import jrain.utils.consts.BaseConst;
import jrain.utils.date.DateUtils;
import jrain.utils.lang.StringUtils;

@Business(name = "IotDeviceCatalogBusiness")
public class IotDeviceCatalogBusiness {
	public SqlRunner getSqlRunner() {
		return FwUtils.getSqlRunnerManger().getSqlRunner(BaseConst.DEFAULT_VALUE);
	}

	@BusinessMethod
	public BusinessResponse add(BusinessRequest request) {
		BusinessResponse response = new BusinessResponse();
		String catalogCode = StringUtils.trimNull(request.getData("catalogCode"));
		Map<String, Object> paramsMap = new HashMap<String,Object>();
		SqlUtils.addConditionEquals(paramsMap, "catalogCode", catalogCode);
		this.setSystemEntCondition(request, paramsMap);
		Map<String, Object> bean = getSqlRunner().query("IotDeviceCatalogBusiness.query.v1", "default", paramsMap);
		if(bean==null){
			BusinessUtils.setId(request.getData());
			//获取登录用户信息
			String appCode = BusinessUtils.getCurrentAppCode(request);
			String tenantCode = BusinessUtils.getCurrenTenantCode(request);
			request.putData("appCode", appCode);
			request.putData("tenantCode", tenantCode);
			request.putData("isLeaf", 1);
			request.putData("createUser", BusinessUtils.getCurrentUserId(request));
			request.putData("createTime", DateUtils.getStrCurrtTime());
			request.putData("lastTime", DateUtils.getStrCurrtTime());
			request.putData("lastUser", BusinessUtils.getCurrentUserId(request));
			int num = getSqlRunner().insert(request.getKey(), "default", request.getData());
			if(num>0){
				//修改pid对应的记录为非叶子节点
				Map<String, Object> updateParamsMap = new HashMap<String,Object>();
				this.setSystemEntCondition(request, updateParamsMap);
				SqlUtils.addConditionEquals(updateParamsMap, "id", request.getData("pid"));
				SqlUtils.addConditionNotEquals(updateParamsMap, "isLeaf", 2);
				updateParamsMap.put("isLeaf", 2);
				getSqlRunner().update("IotDeviceCatalogBusiness.modify.v1", "default", updateParamsMap);
			}
			response.setData(num);
		}else{
			response.setCodeAndMsg(BusinessConst.RES_CODE_ERROR_UNKOWN, "类别编码已经存在！");
		}
		return response;
	}

	@BusinessMethod
	public BusinessResponse modify(BusinessRequest request) {
		BusinessResponse response = new BusinessResponse();
		String id = StringUtils.trimNull(request.getData("id"));
		String catalogCode = StringUtils.trimNull(request.getData("catalogCode"));
		Map<String, Object> paramsMap = new HashMap<String,Object>();
		SqlUtils.addConditionNotEquals(paramsMap, "id", id);
		SqlUtils.addConditionEquals(paramsMap, "catalogCode", catalogCode);
		this.setSystemEntCondition(request, paramsMap);
		Map<String, Object> bean = getSqlRunner().query("IotDeviceCatalogBusiness.query.v1", "default", paramsMap);
		if(bean==null){
			request.putData("lastTime", DateUtils.getStrCurrtTime());
			request.putData("lastUser", BusinessUtils.getCurrentUserId(request));
			SqlUtils.addConditionEquals(request.getData(), BusinessConst.DATA_ID, request.getData(BusinessConst.DATA_ID));
			this.setSystemEntCondition(request,request.getData());
			int num = getSqlRunner().update(request.getKey(), "default", request.getData());
			response.setData(num);
		}else{
			response.setCodeAndMsg(BusinessConst.RES_CODE_ERROR_UNKOWN, "类别编码已经存在！");
		}
		return response;
	}

	@BusinessMethod
	public BusinessResponse remove(BusinessRequest request) {
		BusinessResponse response = new BusinessResponse();
		String id = StringUtils.trimNull(request.getData("id"));
		int num = 0;
		if(!StringUtils.isEmpty(id)) {
			//验证是否有子节点
			Map<String, Object> queryParams = new HashMap<String, Object>();
			this.setSystemEntCondition(request,queryParams);
			SqlUtils.addConditionEquals(queryParams, "pid", id);
			Map<String, Object> bean = getSqlRunner().query("IotDeviceCatalogBusiness.query.v1", "default", queryParams);
			if(bean==null){
				//验证是否有类别下的数据
				Map<String, Object> querySonParams = new HashMap<String, Object>();
				this.setSystemEntCondition(request,querySonParams);
				SqlUtils.addConditionEquals(querySonParams, "catalogId", id);
				Map<String, Object> temp = getSqlRunner().query("IotDeviceBusiness.query.v1", "default", querySonParams);
				if(temp==null){
					this.setSystemEntCondition(request,request.getData());
					SqlUtils.addConditionEquals(request.getData(), BusinessConst.DATA_ID, id);
					//获取被删除的数据
					Map<String, Object> deleteBean = getSqlRunner().query("IotDeviceCatalogBusiness.query.v1", "default", request.getData());
					//删除数据
					num = getSqlRunner().delete(request.getKey(), "default", request.getData());
					if(num>0){
						String pid = StringUtils.trimNull(deleteBean.get("pid"));
						//验证是否有子节点
						Map<String, Object> existsMap = new HashMap<String, Object>();
						this.setSystemEntCondition(request,existsMap);
						SqlUtils.addConditionEquals(existsMap, "pid", pid);
						Map<String, Object> sonBean = getSqlRunner().query("IotDeviceCatalogBusiness.query.v1", "default", existsMap);
						if(sonBean==null){
							//修改删除数据的父节点为叶子节点
							Map<String, Object> updateParams = new HashMap<String, Object>();
							this.setSystemEntCondition(request,updateParams);
							SqlUtils.addConditionEquals(updateParams, "id", pid);
							updateParams.put("isLeaf", 1);
							getSqlRunner().update("IotDeviceCatalogBusiness.modify.v1", "default", updateParams);
						}
					}
					response.setData(num);
				}else{
					response.setCodeAndMsg(BusinessConst.RES_CODE_ERROR_UNKOWN, "请先删除类别下的设备数据！");
				}
			}else{
				response.setCodeAndMsg(BusinessConst.RES_CODE_ERROR_UNKOWN, "请先删除子类别！");
			}
		}else{
			response.setData(num);
		}
		return response;

	}

	@BusinessMethod
	public BusinessResponse query(BusinessRequest request) {
		this.setSystemEntCondition(request,request.getData());
		SqlUtils.addConditionEquals(request.getData(), BusinessConst.DATA_ID, request.getData(BusinessConst.DATA_ID));
		BusinessResponse response = new BusinessResponse();
		Map<String, Object> bean = getSqlRunner().query(request.getKey(), "default", request.getData());
		response.setData(bean);
		return response;
	}

	@BusinessMethod
	public BusinessResponse count(BusinessRequest request) {
		BusinessResponse response = new BusinessResponse();
		this.setSystemEntCondition(request,request.getData());
		Map<String, Object> bean = getSqlRunner().query(request.getKey(), "default", request.getData());
		Number count = null;
		if (bean != null) {
			count = (Number) bean.get("count");
		}
		response.setData(count == null ? 0 : count.intValue());
		return response;
	}

	@BusinessMethod
	public BusinessResponse list(BusinessRequest request) {
		BusinessResponse response = new BusinessResponse();
		this.setSystemEntCondition(request, request.getData());
		SqlUtils.setSqlOrder(request.getData(), "rowSort asc");
		PageObj<List<Map<String, Object>>> bean = getSqlRunner().listPage(request.getKey(), "default", request.getData());
		response.setData(bean.getRows());
		response.setTotal(bean.getTotal());
		return response;
	}
	
	/**
	 * 分类树
	 * @param request
	 * @return
	 */
	@BusinessMethod
	public BusinessResponse listAllSort(BusinessRequest request) {
		BusinessResponse response = new BusinessResponse();
		this.setSystemEntCondition(request,request.getData());
		SqlUtils.setSqlOrder(request.getData(), "rowSort asc");
		List<Map<String, Object>> list = getSqlRunner().list("IotDeviceCatalogBusiness.list.v1", "default", request.getData());
		Map<String, Object> map;
		String id;
		String pid;
		List<Map<String, Object>> childList;
		//以menuId为key存储所有菜单的数据
		Map<String, Map<String, Object>> allCatalogMap = new HashMap<String, Map<String, Object>>();
		//以父节点为key存储所有子节点的数据
		Map<String, List<Map<String, Object>>> childMap = new HashMap<String, List<Map<String, Object>>>();
		for (int i = 0; i < list.size(); i++) {
			map = list.get(i);
			id = StringUtils.trimNull(map.get("id"));
			pid = StringUtils.trimNull(map.get("pid"));
			childList = childMap.get(pid);
			if (childList == null) { 
				childList = new ArrayList<Map<String, Object>>();
				childMap.put(pid, childList);
			}
			childList.add(map);
			allCatalogMap.put(id, map);
		}
		List<Object> retList = getChildMenus("0", allCatalogMap, childMap);
		ParentNode root1 = new ParentNode();
		root1.setDataSourceID("-1");
		root1.setStockName("未分类");
		ParentNode root2 = new ParentNode();
		root2.setDataSourceID("0");
		root2.setStockName("所有分类");
		retList.add(0, root1);
		retList.add(1, root2);
		response.setData(retList);
		response.setTotal(retList.size());
		return response;
	}
	
	public List<Object> getChildMenus(String menuId, Map<String, Map<String, Object>> allMenu,
			Map<String, List<Map<String, Object>>> child) {
		
		ArrayList<Object> retList = new ArrayList<Object>();
		// 1.判断是否是父节点，不是父节点返回空数组
		// 2.是父节点则取子节点的数据
		Map<String, Object> parentNode = allMenu.get(menuId);
		// 父节点不存在返回空数组
		if (parentNode == null) {
			if(menuId.equals("0")) {
				parentNode=new HashMap<String, Object>();
				parentNode.put("isLeaf", "2");
			}else {
				return retList;
			}			
		}
		String isLeaf = StringUtils.trimNull(parentNode.get("isLeaf"));
		// 2非叶子节点
		if (isLeaf.equals("2")) {
			List<Map<String, Object>> childs = child.get(menuId);
			Map<String, Object> mapt;
			// 加载子节点数据
			for (int i = 0; ((childs != null) && (i < childs.size())); i++) {
				mapt = childs.get(i);
				isLeaf = StringUtils.trimNull(mapt.get("isLeaf"));
				if (isLeaf.equals("2")) {
					// 非叶子节点
					ParentNode parent = new ParentNode();
					parent.setDataSourceID(StringUtils.trimNull(mapt.get("id")));
					parent.setStockName(StringUtils.trimNull(mapt.get("catalogName")));
					parent.setExpanded("true");
					parent.setChildren(
							(ArrayList<Object>) getChildMenus(StringUtils.trimNull(mapt.get("id")), allMenu, child));
					retList.add(parent);

				} else {
					// 叶子节点
					LeafNode leaf = new LeafNode();
					leaf.setDataSourceID(StringUtils.trimNull(mapt.get("id")));
					leaf.setStockName(StringUtils.trimNull(mapt.get("catalogName")));
					leaf.setExpanded("true");
					retList.add(leaf);
				}
			}
			return retList;
		} else {
			// 叶子节点，返回空数组
			return retList;
		}
	}
	
	/**
	 * 设置系统企业约束条件
	 * @param paramMap
	 * @return
	 */
	private Map<String, Object> setSystemEntCondition(BusinessRequest request,Map<String, Object> paramMap){
		//获取登录用户信息
		String appCode = BusinessUtils.getCurrentAppCode(request);
		String tenantCode = BusinessUtils.getCurrenTenantCode(request);
		paramMap.put("appCode", appCode);
		paramMap.put("tenantCode", tenantCode);
		return paramMap;
	}
}
